package com.metel.mservice.common.utils;

public class Hex {
	// Byte to HEX
	  static final byte[] HEX_CHAR_TABLE = {
		    (byte)'0', (byte)'1', (byte)'2', (byte)'3',
		    (byte)'4', (byte)'5', (byte)'6', (byte)'7',
		    (byte)'8', (byte)'9', (byte)'a', (byte)'b',
		    (byte)'c', (byte)'d', (byte)'e', (byte)'f'
	  };    
	  public static String getHexString(byte[] raw){
		  byte[] hex = new byte[2 * raw.length];
		  int index = 0;

		  for (byte b : raw) {
			  int v = b & 0xFF;
		      hex[index++] = HEX_CHAR_TABLE[v >>> 4];
		      hex[index++] = HEX_CHAR_TABLE[v & 0xF];
		  }
		  try{
			  return new String(hex, "ASCII");
		  }catch(Exception e){
			 // e.printStackTrace();
			  return null;
		  }
	  }	
	  
	  static final String HEX_STRING  = "0123456789ABCDEF";
	  public static byte[] convertHexadecimal2Binary(byte[] hex) {
		  int block = 0;
		  byte[] data = new byte[hex.length / 2];
		  int index = 0;
		  boolean next = false;
		 
		  for (int i=0; i<hex.length; i++) {
		    block <<= 4;
		    int pos = HEX_STRING.indexOf(Character.toUpperCase((char) hex[i]));
		    if (pos > -1) block += pos;
		 
		    if (next) {
		      data[index] = (byte)(block & 0xff );
		      index++;
		      next = false;
		    } else next = true;
		  }
		 
		  return data;
		}	  
}
